package com.baixun.gassystem.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baixun.gascommon.config.ApiConfig;
import com.baixun.gascommon.utils.HttpClientUtil;
import com.baixun.gascommon.utils.RedisUtils;
import com.baixun.gassystem.mapper.SysAlgorithmInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.*;
import java.util.HashMap;

@Service
public class SuanfaPointService {

    private static final String TOKEN_KEY = "SAAS_SESSION_TOKEN";

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ApiService apiService;

    @Autowired
    private SysAlgorithmInfoMapper sysAlgorithmInfoMapper;

    public JSONArray getSuanfaPoints() throws Exception {
        String catalogueIds = apiService.treeSearch();
        JSONObject json = JSONObject.parseObject(catalogueIds);
        Object dataObject = json.get("data");
        JSONArray data;

        if (dataObject instanceof JSONArray) {
            data = (JSONArray) dataObject;
        } else if (dataObject instanceof JSONObject) {
            data = new JSONArray();
            data.add(dataObject);
        } else {
            throw new Exception("Expected 'data' to be either a JSONArray or JSONObject, but found: " +
                    (dataObject != null ? dataObject.getClass().getSimpleName() : "null"));
        }

        if (data.isEmpty()) {
            throw new Exception("No data found in catalogueIds JSON.");
        }

        String token = redisUtils.get(TOKEN_KEY);
        if (token == null) {
            throw new Exception("No valid token found in Redis.");
        }

        for (Object datum : data) {
            Long pointId;

            // 检查 datum 是否为 JSONObject 并提取所需的 ID 字段
            if (datum instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) datum;
                // 提取需要的 id 字段作为 pointId，确保是数值类型
                if (jsonObject.containsKey("id")) {
                    pointId = jsonObject.getLong("id");
                } else {
                    System.err.println("No valid 'id' found in JSON object: " + jsonObject);
                    continue; // 跳过无效数据
                }
            } else if (datum instanceof Integer) {
                pointId = ((Integer) datum).longValue();
            } else {
                try {
                    pointId = Long.valueOf(datum.toString());
                } catch (NumberFormatException e) {
                    System.err.println("Invalid format for pointId: " + datum);
                    continue; // 跳过无效数据
                }
            }

            String abilitiesUrl = ApiConfig.DOMAIN + "/api/v2/ai/apps/points/" + pointId + "/abilities";

            HashMap<String, String> headers = new HashMap<>();
            headers.put("Cookie", "SAAS_SESSION=" + token);
            headers.put("Content-Type", "application/json; charset=UTF-8");

            String response = HttpClientUtil.sendGetRequest(abilitiesUrl, headers);
            if (response == null || response.isEmpty()) {
                System.err.println("Failed to get response for pointId: " + pointId);
                continue;
            }

            JSONObject responseObject = JSONObject.parseObject(response);
            System.out.println("Response for pointId " + pointId + ": " + responseObject);
        }

        System.out.println("data=" + data);
        return data;
    }
//@Scheduled(fixedRate = 86400000)
    //  此方法弃用直接调取evsapi接口
public void saveAlgorithmDataToDatabase() throws Exception {
    JSONArray dataArray = getSuanfaPoints();

    if (dataArray == null || dataArray.isEmpty()) {
        throw new Exception("Data array is null or empty.");
    }


        // 递归解析每个节点
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject node = dataArray.getJSONObject(i);
            saveNodeAndChildren(node);  // 递归保存节点及其子节点
        }
}

    /**
     * 递归遍历节点及其子节点，并保存必要的信息到数据库
     */
    @Transactional
    public void saveNodeAndChildren(JSONObject node) {
        // 提取所需的字段
        String type = node.getString("type");
        String name = node.getString("name");
        String description = node.getString("description");

        // 检查字段是否为空
        if (type == null || name == null || description == null) {
            System.err.println("Missing required fields in node: " + node);
            return;
        }

        // 检查数据库中是否已存在相同记录
        int count = sysAlgorithmInfoMapper.countByTypeAndName(type, name);
        boolean exists = count > 0;

        // 插入新记录（如果不存在）
        if (!exists) {
            sysAlgorithmInfoMapper.insertSysAlgorithmInfo(type, name, description);
        }

        // 递归处理子节点
        JSONArray children = node.getJSONArray("children");
        if (children != null) {
            for (int j = 0; j < children.size(); j++) {
                JSONObject childNode = children.getJSONObject(j);
                saveNodeAndChildren(childNode);  // 递归处理每个子节点
            }
        }
    }
}
